package com.zzg.lucene.delete;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;

public class LuceneDelete {

	public static void main(String[] args) throws IOException{
		RAMDirectory ramDirectory = new RAMDirectory();
	    IndexWriter indexWriter = new IndexWriter(ramDirectory, new IndexWriterConfig(new StandardAnalyzer()));
	    Document document = new Document();
	    document.add(new IntPoint("ID", 1));
	    indexWriter.addDocument(document);
	    indexWriter.commit();
	    
	    // 删除ID为1的Document对象(失败删除)
	    indexWriter.deleteDocuments(new Term("ID", "1"));
	    indexWriter.commit();
	    
	    // 判断ID为1的Document对象是否删除成功
	    DirectoryReader open = DirectoryReader.open(ramDirectory);
	    IndexSearcher indexSearcher = new IndexSearcher(open);
	    Query query = IntPoint.newExactQuery("ID", 1);
	    TopDocs search = indexSearcher.search(query, 10);
	    //条件查询命中数量(判断是否大于1)
	    System.out.println("第一次删除:" + search.totalHits);
	    
	  //使用IntPoint.newExactQuery删除(成功删除)
	    indexWriter.deleteDocuments(query);
	    indexWriter.commit();
	    indexSearcher = new IndexSearcher(DirectoryReader.openIfChanged(open));
	    search = indexSearcher.search(query, 10);
	    //条件查询命中数量(判断是否大于1)
	    System.out.println("第二次删除:" + search.totalHits);
	}

}
